package com.oracle.lingshangejia.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.IdCardBean;
import com.oracle.lingshangejia.bean.SignBean;
import com.oracle.lingshangejia.bean.SocialBean;
import com.oracle.lingshangejia.utils.AppManagerDelegate;
import com.oracle.lingshangejia.utils.FileUtil;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;
import com.oracle.lingshangejia.view.RecognizeService;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



/**
 * 医保卡签约
 */
public class CarteVitalActivity  extends BaseActivity implements View.OnClickListener {
    private ImageButton ib_back;
    private LinearLayout ll_cartevital_z;//医保卡正面
    private ImageView iv_ybk_img;//医保卡照片
    private LinearLayout ll_cartevital_f;//医保卡反面
    private ImageView iv_cartevital_img;
    private RelativeLayout rl_cartevital_ok;
    private boolean hasGotToken=false;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106;
    private static final int REQUEST_IMAGE = 200;
    private List<LocalMedia> selectList = new ArrayList<>();
    private TextView tv_cartevital_num;
    @Override
    public int intiLayout() {
        return R.layout.activity_cartevital;
    }

    @Override
    public void initView() {
        ib_back=findViewById(R.id.ib_back);
        tv_cartevital_num=findViewById(R.id.tv_cartevital_num);
        ll_cartevital_z=findViewById(R.id.ll_cartevital_z);
        ll_cartevital_f=findViewById(R.id.ll_cartevital_f);
        iv_cartevital_img=findViewById(R.id.iv_cartevital_img);
        rl_cartevital_ok=findViewById(R.id.rl_cartevital_ok);
        iv_ybk_img=findViewById(R.id.iv_ybk_img);
        ib_back.setOnClickListener(this);
        ll_cartevital_z.setOnClickListener(this);
        ll_cartevital_f.setOnClickListener(this);
        rl_cartevital_ok.setOnClickListener(this);
        initAccessTokenWithAkSk();
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back: //返回S
                finish();
                break;
            case R.id.ll_cartevital_z:  //医保卡正面S
                if (!checkTokenStatus()) {
                    return;
                }
                Intent intent = new Intent(CarteVitalActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);
                break;
            case R.id.ll_cartevital_f://z医保卡反面S
                // 进入相册 以下是例子：用不到的api可以不写
                PictureSelector.create(CarteVitalActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .withAspectRatio(1,1)
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .compressSavePath(getPath())//压缩图片保存地址
                        .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                        .previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .isDragFrame(false)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.rl_cartevital_ok:  //确定
                String idnumber= (String) SpUtils.get(CarteVitalActivity.this,"idnumber1","");
                if(TextUtils.isEmpty(idnumber)||idnumber.equals("")){
                    Toast.makeText(CarteVitalActivity.this,"请先扫描医保卡",Toast.LENGTH_SHORT).show();
                    return;
                }
                //判断是否添加手持身份证照片 （身份证正面照片 有身份证肯定是扫描过一定存在）
                getNetIdentify(idnumber);
                break;
        }
    }
    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(CarteVitalActivity.this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
                hasGotToken=true;
                SpUtils.put(CarteVitalActivity.this,"ocrtoken",token);
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
            }
        }, getApplicationContext(), "IOfn71lXjSrT9s2vgc7WShhj", "f6KYzIK9rbRYBDG8vkAjCVI0b24BVnS7");
    }
    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }
    /**
     * 以license文件方式初始化
     */
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
        }
    }
    private void alertText(final String title, final String message) {

        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson=new Gson();
                SocialBean socialBean=gson.fromJson(message, SocialBean.class);
                if(socialBean.getWords_result().size()==0){
//                    Glide.with(CarteVitalActivity.this)
//                            .load(R.drawable.ic_idsigning_id1)
//                            .into(iv_ybk_img);
                    tv_cartevital_num.setVisibility(View.GONE);
                    Toast.makeText(CarteVitalActivity.this,"请扫描正确的社保卡",Toast.LENGTH_SHORT).show();
                }else{
                    boolean isCarteVital=false; //默认不是社保卡
                    String number="";
                    String sex="";
                    String name="";
                    for(int i=0;i<socialBean.getWords_result().size();i++){
                        String word=socialBean.getWords_result().get(i).getWords();
                        if (word.contains("社会保障号码")) {
                            number=word.substring(6,24);
                            isCarteVital=true;
                        }
                        if(word.contains("性别")){
                            sex=word.substring(2,3);
                        }
                        if(word.contains("姓名")){
                            name=word.substring(2,4);
                        }
                    }
                   if(isCarteVital){
                       tv_cartevital_num.setVisibility(View.VISIBLE);
                       showTestIdNumberDialog(number,name,sex);
                   }else{
                       tv_cartevital_num.setVisibility(View.GONE);
                       Toast.makeText(CarteVitalActivity.this,"请扫描正确的社保卡",Toast.LENGTH_SHORT).show();
                   }

//                    Glide.with(CarteVitalActivity.this)
//                            .load(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath())
//                            .into(iv_ybk_img);
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        tv_cartevital_num.setVisibility(View.GONE);
    }

    /**
     *
     * 弹出检查身份证号是否正确对话框
     * @param number  身份证号
     * @param name  姓名
     * @param sex  性别
     */
    private void showTestIdNumberDialog(final String number, String name, String sex){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.testidnumber_dialog, null);
        TextView tv_test_name=view_dialog.findViewById(R.id.tv_test_name);
        TextView tv_test_sex=view_dialog.findViewById(R.id.tv_test_sex);
        TextView tv_test_number=view_dialog.findViewById(R.id.tv_test_number);
        TextView tv_test_cancle=view_dialog.findViewById(R.id.tv_test_cancle);
        TextView tv_test_ok=view_dialog.findViewById(R.id.tv_test_ok);
        tv_test_name.setText("姓名："+name);
        tv_test_sex.setText("性别："+sex);
        tv_test_number.setText("身份证号："+number);
        tv_test_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_test_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpUtils.put(CarteVitalActivity.this,"idnumber1",number);
              //  getNetIdentify(number);
                dialog.dismiss();
            }
        });
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.CENTER);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
    /**
     * 身份证认证接口
     * @param idnumber  身份证号码
     */
    private void getNetIdentify(String idnumber) {
        //String token= (String) SpUtils.get(IdCardActivity.this,"token","");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("sfzh",idnumber);
        OkHttpUtils.getNetWork(CarteVitalActivity.this, Constant.baseurl+"online/isSigning",map,handler);
    }
    /**
     * 弹出签约对话框
     */
    private void showIdCardSignDialog(final String number, String name, String sex, final int id){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.idcardsign_dialog, null);
        TextView tv_sign_name=view_dialog.findViewById(R.id.tv_sign_name);
        TextView tv_sign_sex=view_dialog.findViewById(R.id.tv_sign_sex);
        TextView tv_sign_number=view_dialog.findViewById(R.id.tv_sign_number);
        TextView tv_sign_cancle=view_dialog.findViewById(R.id.tv_sign_cancle);
        TextView tv_sign_ok=view_dialog.findViewById(R.id.tv_sign_ok);
        tv_sign_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_sign_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //签约接口
                int ysid= (int) SpUtils.get(CarteVitalActivity.this,"ysid",-1);
                getNetToSign(id,ysid);
            }
        });
        tv_sign_name.setText("姓名："+name);
        tv_sign_sex.setText("性别："+sex);
        tv_sign_number.setText("社会保障号码："+number);
        SpUtils.put(CarteVitalActivity.this,"shebao_name",name);
        SpUtils.put(CarteVitalActivity.this,"shebao_sex",sex);
        SpUtils.put(CarteVitalActivity.this,"shebao_number",number);
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.CENTER);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
    private  void getNetToSign(int id, int ysid){
        HashMap<Object,Object> map = new HashMap<>();
        map.put("jmId",id);
        map.put("ysId",ysid);
        OkHttpUtils.getNetWork(CarteVitalActivity.this, Constant.baseurl+"online/signing",map,signhandler);
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    try {
                        setData(s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(CarteVitalActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(CarteVitalActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(CarteVitalActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private void setData(String s) throws Exception{
        SpUtils.put(this,"idnumber1","");
        Gson gson=new Gson();
        IdCardBean bean=gson.fromJson(s, IdCardBean.class);
        if(bean.getCode()==0){
            //直接跳转新增居民档案页面 SpUtils.put(CarteVitalActivity.this,"shebao_name",name);
            //        SpUtils.put(CarteVitalActivity.this,"shebao_sex",sex);
            //        SpUtils.put(CarteVitalActivity.this,"shebao_number",number);
            String shebao_name= (String) SpUtils.get(CarteVitalActivity.this,"shebao_name","");
            String shebao_sex= (String) SpUtils.get(CarteVitalActivity.this,"shebao_sex","");
            String shebao_number= (String) SpUtils.get(CarteVitalActivity.this,"shebao_number","");
            Intent intent=new Intent(CarteVitalActivity.this, ArchivesActivity.class);
            intent.putExtra("shebao_name",shebao_name);
            intent.putExtra("shebao_sex",shebao_sex);
            intent.putExtra("shebao_number",shebao_number);
            startActivity(intent);
        }else if(bean.getCode()==1){
            if(bean.getData().getSfqy()==0){  //0未签约 (弹出签约对话框)
                //number name sex
                String sex;
                if(bean.getData().getXb()==1){
                    sex="男";
                }else{
                    sex="女";
                }
                showIdCardSignDialog(bean.getData().getSfzh(),bean.getData().getXm(),sex,bean.getData().getId());
            }else{  //已签约 跳转首页
                Toast.makeText(CarteVitalActivity.this,"您已签约",Toast.LENGTH_SHORT).show();
              //  AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
                AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
                finish();
            }
        }else if(bean.getCode()==10){  //token过期
            //AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
            finish();
            AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
            AppManagerDelegate.getInstance().finishActivity(MainActivity.class);
            SpUtils.put(CarteVitalActivity.this,"token","");
            SpUtils.put(CarteVitalActivity.this,"isLogin",false);
            Intent intent=new Intent(CarteVitalActivity.this, LoginActivity.class);
            startActivity(intent);
        }else{
            Toast.makeText(CarteVitalActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
        }
    }
    private Handler signhandler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    Gson gson=new Gson();
                    SignBean bean=gson.fromJson(s, SignBean.class);
                    if(bean.getCode()==0){  //签约成功
                        Toast.makeText(CarteVitalActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        //AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
                        AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
                        finish();
                    }else if(bean.getCode()==1){  //签约失败
                        Toast.makeText(CarteVitalActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(CarteVitalActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(CarteVitalActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(CarteVitalActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(CarteVitalActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private void infoPopText(final String result) {
        Log.e("result",result);
        alertText("", result);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recGeneralBasic(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            infoPopText(result);
                        }
                    });
        }
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK){
            // 图片选择结果回调
            selectList = PictureSelector.obtainMultipleResult(data);
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

            for (LocalMedia media : selectList) {
                Log.i("图片-----》", media.getPath());
                File file=new File(media.getCutPath());
                //设置图片
                Glide.with(CarteVitalActivity.this)
                    .load(file.getPath())
                    .into(iv_cartevital_img);
            }
        }

//            final List<String> path = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
//            //设置图片
//            Glide.with(CarteVitalActivity.this)
//                    .load(path.get(0))
//                    .into(iv_cartevital_img);


    }
    @Override
    protected void onDestroy() {
        // 释放本地质量控制模型
        // 释放内存资源
        OCR.getInstance(this).release();
        super.onDestroy();
    }
}
